package com.example.zbh.dsliao.model;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.zbh.dsliao.db.entity.NewSong;
import com.example.zbh.dsliao.model.entity.NetSongList;
import com.example.zbh.dsliao.model.modelinterface.ManagerDataListener;
import com.example.zbh.dsliao.presenter.presenterinterface.HandMessageListener;
import com.example.zbh.dsliao.utils.net.VolleySingleton;
import com.google.gson.Gson;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zbh on 15/12/7.
 */
public class SongListModel implements ManagerDataListener {
    @Override
    public void sendResult(String url, final HandMessageListener messageListener) {

        JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        if (response != null && response.has("data")) {
//                            customDialog.dismiss();
                            List<NetSongList> list = new ArrayList<>();
                            try {
                                JSONArray array = response.getJSONArray("data");
                                Gson gson = new Gson();
                                list = new ArrayList<NetSongList>();
                                for (int i = 0; i < array.length(); i++) {
                                    String str = array.getString(i);
                                    NetSongList e = gson.fromJson(str, NetSongList.class);
                                    list.add(e);
                                }
                                messageListener.handResult(list);
//                                adapter.addData(list);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        VolleySingleton.getInstance().addRequest(request);
    }
}
